package org.giovanolli.mumi.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.giovanolli.mumi.dao.BillDao;
import org.giovanolli.mumi.dao.Dao;
import org.giovanolli.mumi.entities.AttentionTime;
import org.giovanolli.mumi.entities.Bill;
import org.giovanolli.mumi.entities.BillDetail;
import org.giovanolli.mumi.entities.Movement;
import org.giovanolli.mumi.entities.MovementType;
import org.giovanolli.mumi.entities.Patient;
import org.giovanolli.mumi.service.AttentionTimeService;
import org.giovanolli.mumi.service.BillService;
import org.giovanolli.mumi.service.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

// TODO: Auto-generated Javadoc
/**
 * The Class BillServiceImpl.
 */
@Service("billService")
public class BillServiceImpl extends AbstractService<Bill> implements BillService {

	/** The attention time dao. */
	@Autowired
	private BillDao billDao;

	@Autowired
	private AttentionTimeService attentionTimeService;

	@Autowired
	private PatientService patientService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.giovanolli.mumi.service.BaseObjectService#getServiceDao()
	 */
	protected Dao<Bill> getServiceDao() {
		return billDao;
	}

	@Override
	public List<BillDetail> getNonBilledDetails(Patient patient) {
		List<BillDetail> billDetails = new ArrayList<BillDetail>();
		for (AttentionTime attentionTime : attentionTimeService.getNonBilledAttentionTimes(patient)) {
			BillDetail detail = new BillDetail();
			/* detail.setAttentionTime(attentionTime); */
			/* detail.setAttentionType(attentionTime.getAttentionType()); */
			detail.setSpecialistFee(attentionTime.getSpecialistFee());
			billDetails.add(detail);
		}
		return billDetails;
	}

	public BillDao getBillDao() {
		return billDao;
	}

	@Override
	public void saveEntity(Bill entity) {
		Patient patient = entity.getPatient();
		for (BillDetail billDetail : entity.getBillDetails()) {
			for (int i = 0; i < billDetail.getQuantity(); i++) {
				Movement movement = new Movement();
				movement.setDate(new Date());
				movement.setFee(billDetail.getSpecialistFee().getAmount());
				movement.setMovementType(MovementType.POSITIVE);
				movement.setAttentionTypeMode(billDetail.getSpecialistFee().getAttentionTypeMode());
				movement.setMonth(billDetail.getPaidMonth());
				movement.setYear(billDetail.getPaidYear());
				movement.setSpecialistFee(billDetail.getSpecialistFee());
				patient.getMovements().add(movement);
			}
		}

		patientService.saveEntity(patient);
		super.saveEntity(entity);
	}

}
